package com.halfsword.creativecraft.gui.machine;

import com.halfsword.creativecraft.CreativeCraft;
import com.halfsword.creativecraft.block.custom.machine.blockentity.SteamPowerCrusherBlockEntity;
import com.halfsword.creativecraft.modules.StagedSteamMechanism;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;

import java.text.DecimalFormat;
import java.util.List;

public class SteamCrusherScreened extends AbstractContainerScreen<SteamCrusherMenu> {

    public static final ResourceLocation TEXTURE =
            ResourceLocation.fromNamespaceAndPath(CreativeCraft.MOD_ID, "textures/gui/steam_power_crusher.png");

    // 水槽相关常量
    private static final int WATER_TANK_1_X = 7;
    private static final int WATER_TANK_1_Y = 9;
    private static final int WATER_TANK_WIDTH = 16;
    private static final int WATER_TANK_HEIGHT = 33;

    private static final int WATER_TANK_2_X = 26;
    private static final int WATER_TANK_2_Y = 9;

    // 进度条相关常量
    private static final int PROGRESS_WIDTH = 35;
    private static final int PROGRESS_HEIGHT = 21;
    private static final int PROGRESS_X = 65;
    private static final int PROGRESS_Y = 30;
    private static final int PROGRESS_U = 176;
    private static final int PROGRESS_V = 14;

    // 状态条（蒸汽压力条）相关常量
    private static final int STEAM_BAR_X = 86;
    private static final int STEAM_BAR_Y = 9;
    private static final int STEAM_BAR_WIDTH = 45;
    private static final int STEAM_BAR_HEIGHT = 8;

    // 燃料指示器相关常量
    private static final int FUEL_1_X = 8;
    private static final int FUEL_1_Y = 46;
    private static final int FUEL_2_X = 28;
    private static final int FUEL_2_Y = 46;
    private static final int FUEL_WIDTH = 12;
    private static final int FUEL_HEIGHT = 12;
    private static final int FUEL_U = 176;
    private static final int FUEL_V = 1;

    // 水纹理位置
    private static final int WATER_TEXTURE_U = 176;
    private static final int WATER_TEXTURE_V = 40;

    private static final DecimalFormat TORQUE_FORMAT = new DecimalFormat("0.0");
    private static final DecimalFormat PERCENT_FORMAT = new DecimalFormat("0%");

    public SteamCrusherScreened(SteamCrusherMenu menu, Inventory playerInventory, Component title) {
        super(menu, playerInventory, title);
        this.imageWidth = 176;
        this.imageHeight = 166;
        this.inventoryLabelY = 10000;
        this.titleLabelY = 10000;
    }

    @Override
    protected void init() {
        super.init();
        this.titleLabelX = (this.imageWidth - this.font.width(this.title)) / 2;
    }

    @Override
    protected void renderBg(GuiGraphics guiGraphics, float partialTick, int mouseX, int mouseY) {
        RenderSystem.setShader(GameRenderer::getPositionTexShader);
        RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
        RenderSystem.setShaderTexture(0, TEXTURE);

        int x = (width - imageWidth) / 2;
        int y = (height - imageHeight) / 2;

        // 绘制背景
        guiGraphics.blit(TEXTURE, x, y, 0, 0, imageWidth, imageHeight);

        // 绘制水槽（流动水效果）
        renderWaterTanks(guiGraphics, x, y);

        // 绘制配方进度条
        if (menu.isWorking()) {
            renderProgressBar(guiGraphics, x, y);
        }

        // 绘制蒸汽压力条
        renderSteamBar(guiGraphics, x, y);

        // 绘制燃料指示器
        renderFuelIndicators(guiGraphics, x, y);

        // 在蒸汽条上方绘制当前阶段文字
        renderStageText(guiGraphics, x, y);
    }

    // 绘制水槽
    private void renderWaterTanks(GuiGraphics guiGraphics, int guiLeft, int guiTop) {
        // 计算水槽填充高度（基于水位百分比）
        float waterPercent1 = menu.getWaterTank1Percent();
        float waterPercent2 = menu.getWaterTank2Percent();

        int waterHeight1 = (int) (waterPercent1 * WATER_TANK_HEIGHT);
        int waterHeight2 = (int) (waterPercent2 * WATER_TANK_HEIGHT);

        // 绘制水槽1的水 - 从底部向上填充
        if (waterHeight1 > 0) {
            guiGraphics.blit(
                    TEXTURE,
                    guiLeft + WATER_TANK_1_X,
                    guiTop + WATER_TANK_1_Y + (WATER_TANK_HEIGHT - waterHeight1),
                    WATER_TEXTURE_U,
                    WATER_TEXTURE_V + (WATER_TANK_HEIGHT - waterHeight1),
                    WATER_TANK_WIDTH,
                    waterHeight1
            );
        }

        // 绘制水槽2的水 - 从底部向上填充
        if (waterHeight2 > 0) {
            guiGraphics.blit(
                    TEXTURE,
                    guiLeft + WATER_TANK_2_X,
                    guiTop + WATER_TANK_2_Y + (WATER_TANK_HEIGHT - waterHeight2),
                    WATER_TEXTURE_U,
                    WATER_TEXTURE_V + (WATER_TANK_HEIGHT - waterHeight2),
                    WATER_TANK_WIDTH,
                    waterHeight2
            );
        }
    }

    // 渲染配方进度条
    private void renderProgressBar(GuiGraphics guiGraphics, int guiLeft, int guiTop) {
        int progress = (int) (menu.getProgressPercent() * PROGRESS_WIDTH);
        guiGraphics.blit(
                TEXTURE,
                guiLeft + PROGRESS_X,
                guiTop + PROGRESS_Y,
                PROGRESS_U,
                PROGRESS_V,
                progress,
                PROGRESS_HEIGHT
        );
    }

    // 渲染蒸汽压力条
    private void renderSteamBar(GuiGraphics guiGraphics, int guiLeft, int guiTop) {
        float pressurePercent = menu.getSteamPressurePercent();
        int steamWidth = (int) (pressurePercent * STEAM_BAR_WIDTH);

        // 绘制蒸汽条填充
        guiGraphics.blit(
                TEXTURE,
                guiLeft + STEAM_BAR_X,
                guiTop + STEAM_BAR_Y,
                0, // 假设蒸汽条纹理在左上角
                0,
                steamWidth,
                STEAM_BAR_HEIGHT
        );
    }

    // 渲染燃料指示器（两个燃烧条）
    private void renderFuelIndicators(GuiGraphics guiGraphics, int guiLeft, int guiTop) {
        // 计算燃料百分比
        int maxFuel = SteamPowerCrusherBlockEntity.MIN_FUEL * 10;
        float fuelPercent = Math.min(1.0f, (float) menu.getFuelLevel() / maxFuel);
        int fuelHeight = (int) (fuelPercent * FUEL_HEIGHT);

        // 绘制第一个燃料指示器 - 从底部向上填充
        if (fuelHeight > 0) {
            guiGraphics.blit(
                    TEXTURE,
                    guiLeft + FUEL_1_X,
                    guiTop + FUEL_1_Y + (FUEL_HEIGHT - fuelHeight),
                    FUEL_U,
                    FUEL_V + (FUEL_HEIGHT - fuelHeight),
                    FUEL_WIDTH,
                    fuelHeight
            );
        }

        // 绘制第二个燃料指示器 - 从底部向上填充
        if (fuelHeight > 0) {
            guiGraphics.blit(
                    TEXTURE,
                    guiLeft + FUEL_2_X,
                    guiTop + FUEL_2_Y + (FUEL_HEIGHT - fuelHeight),
                    FUEL_U,
                    FUEL_V + (FUEL_HEIGHT - fuelHeight),
                    FUEL_WIDTH,
                    fuelHeight
            );
        }
    }

    // 在蒸汽条上方渲染当前阶段文字
    private void renderStageText(GuiGraphics guiGraphics, int guiLeft, int guiTop) {
        StagedSteamMechanism.Stage stage = menu.getStage();
        String stageText = getStageText(stage);
        int textWidth = this.font.width(stageText);
        int textX = guiLeft + STEAM_BAR_X + (STEAM_BAR_WIDTH - textWidth) / 2;
        int textY = guiTop + STEAM_BAR_Y - 3; // 向上移动更多，避免重叠

        int color = switch (stage) {
            case RISING -> 0xFFDAA520; // 金色
            case BALANCED -> 0xFF00FF00;   // 绿色
            case DECLINING -> 0xFFFFA500; // 橙色
            default -> 0xFFFFFFFF;         // 白色
        };

        guiGraphics.drawString(this.font, stageText, textX, textY, color, false);
    }

    @Override
    public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
        renderBackground(guiGraphics);
        super.render(guiGraphics, mouseX, mouseY, partialTick);
        renderTooltip(guiGraphics, mouseX, mouseY);

        int guiLeft = (width - imageWidth) / 2;
        int guiTop = (height - imageHeight) / 2;

        // 蒸汽压力条提示
        if (isHovering(STEAM_BAR_X, STEAM_BAR_Y, STEAM_BAR_WIDTH, STEAM_BAR_HEIGHT, mouseX, mouseY)) {
            List<Component> tooltip = List.of(
                    Component.translatable("tooltip.steam_crusher.torque", TORQUE_FORMAT.format(menu.getTorque())),
                    Component.translatable("tooltip.steam_crusher.stage", getStageText(menu.getStage())),
                    Component.translatable("tooltip.steam_crusher.pressure", PERCENT_FORMAT.format(menu.getSteamPressurePercent()))
            );
            guiGraphics.renderComponentTooltip(this.font, tooltip, mouseX, mouseY);
        }

        // 燃料指示器提示
        if (isHovering(FUEL_1_X, FUEL_1_Y, FUEL_WIDTH, FUEL_HEIGHT, mouseX, mouseY) ||
                isHovering(FUEL_2_X, FUEL_2_Y, FUEL_WIDTH, FUEL_HEIGHT, mouseX, mouseY)) {
            List<Component> tooltip = List.of(
                    Component.translatable("tooltip.steam_crusher.fuel", menu.getFuelLevel())
            );
            guiGraphics.renderComponentTooltip(this.font, tooltip, mouseX, mouseY);
        }

        // 水槽提示
        if (isHovering(WATER_TANK_1_X, WATER_TANK_1_Y, WATER_TANK_WIDTH, WATER_TANK_HEIGHT, mouseX, mouseY)) {
            List<Component> tooltip = List.of(
                    Component.translatable("tooltip.steam_crusher.water_tank1",
                            menu.getWaterTank1Level(),
                            SteamPowerCrusherBlockEntity.MAX_WATER_TANK_CAPACITY)
            );
            guiGraphics.renderComponentTooltip(this.font, tooltip, mouseX, mouseY);
        }

        if (isHovering(WATER_TANK_2_X, WATER_TANK_2_Y, WATER_TANK_WIDTH, WATER_TANK_HEIGHT, mouseX, mouseY)) {
            List<Component> tooltip = List.of(
                    Component.translatable("tooltip.steam_crusher.water_tank2",
                            menu.getWaterTank2Level(),
                            SteamPowerCrusherBlockEntity.MAX_WATER_TANK_CAPACITY)
            );
            guiGraphics.renderComponentTooltip(this.font, tooltip, mouseX, mouseY);
        }

        // 进度条提示
        if (menu.isWorking() && isHovering(PROGRESS_X, PROGRESS_Y, PROGRESS_WIDTH, PROGRESS_HEIGHT, mouseX, mouseY)) {
            int progress = menu.getProgress();
            int maxProgress = menu.getMaxProgress();
            int progressPercent = (int)((float)progress / maxProgress * 100);
            float remainingSeconds = (maxProgress - progress) / 20f;

            List<Component> tooltip = List.of(
                    Component.translatable("tooltip.steam_crusher.progress", progressPercent),
                    Component.translatable("tooltip.steam_crusher.remaining", TORQUE_FORMAT.format(remainingSeconds))
            );
            guiGraphics.renderComponentTooltip(this.font, tooltip, mouseX, mouseY);
        }
    }

    private String getStageText(StagedSteamMechanism.Stage stage) {
        return switch (stage) {
            case RISING -> "预热中";
            case BALANCED -> "平衡状态";
            case DECLINING -> "下降";
            default -> "空闲";
        };
    }
}